package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/pkg/xlog"
	"github.com/go-pay/gopay/wechat/v3"
	"net/http"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
)

// 微信支付
func Wechatpayvywdvip(ctx *gin.Context) {
	request := PayBody{}
	ctx.ShouldBind(&request)

	uid := request.Uid
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)

	orderno := Generate(time.Time{})

	orderadd := models.Ywdvipbuy{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Status:  1,
		Orderno: orderno,
		Price:   1299,
	}
	data_source.Db.Create(&orderadd)
	money2 := 1299 * 100
	if uid == 157030 || uid == 26280 {
		money2 = 1
	}

	client, err := wechat.NewClientV3(mchIdywd, mchCertificateSerialNumberywd, mchAPIv3Key, mchPrivateKeyywd)
	fmt.Println(client)
	if err != nil {
		xlog.Error(err)
		return
	}
	err = client.AutoVerifySign()
	if err != nil {
		xlog.Error(err)
		return
	}
	expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	bm.Set("appid", appidywd).
		Set("mchid", mchIdywd).
		Set("description", "充值余额").
		Set("out_trade_no", orderno).
		Set("time_expire", expire).
		Set("notify_url", pturl+"/user/wechatNotifywvip").
		SetBodyMap("amount", func(bm gopay.BodyMap) {
			bm.Set("total", money2).
				Set("currency", "CNY")
		}).
		SetBodyMap("payer", func(bm gopay.BodyMap) {
			bm.Set("openid", user.Ywdgzheopenid)
		})

	wxRsp, err := client.V3TransactionJsapi(ctx, bm)
	jsapi, err := client.PaySignOfJSAPI(appidywd, wxRsp.Response.PrepayId)
	if err != nil {
		xlog.Error(err)
		return
	}
	fmt.Print(wxRsp)
	fmt.Print(jsapi)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    jsapi,
	})
	return
}
func WechatNotifywvip(c *gin.Context) {

	fmt.Println(c.Request)
	notifyReq, err := wechat.V3ParseNotify(c.Request)
	fmt.Println("notifyReq", notifyReq)
	if err != nil {
		xlog.Error(err)
		return
	}
	result, err := notifyReq.DecryptCipherText(mchAPIv3Key)
	fmt.Println("result.TradeState", result.TradeState)
	fmt.Println("result.TradeState", result.OutTradeNo)
	if result.TradeState == "SUCCESS" { // 验证成功
		//fmt.Println(notifyRsp["out_trade_no"].(string))
		Zhifupayvip(result.OutTradeNo)
		c.String(200, "success")
		return
	}
	c.String(200, "error")
	return
}

// 支付完成
func Zhifupayvip(order string) {
	var orderinfo models.Ywdvipbuy
	data_source.Db.Where("orderno = ?", order).First(&orderinfo)
	data_source.Db.Model(&models.Ywdvipbuy{}).Where("orderno = ?", order).Update("status", 2)

	var user_info models.User
	data_source.Db.Where("id = ?", orderinfo.Uid).First(&user_info)

	if user_info.Vip == 1 {
		userupdate := models.User{
			Vip:        2,
			Vipinttime: time.Now().Unix(),
			Vipendtime: time.Now().Unix() + 86400*365,
		}
		data_source.Db.Where("id = ?", orderinfo.Uid).Updates(&userupdate)
	} else if user_info.Vip == 2 {
		userupdate := models.User{
			Vip:        2,
			Vipendtime: user_info.Vipendtime + 86400*365,
		}
		data_source.Db.Where("id = ?", orderinfo.Uid).Updates(&userupdate)
	}

}

// 微信支付
func Wechatpayvywdvipapp(ctx *gin.Context) {
	request := PayBody{}
	ctx.ShouldBind(&request)

	uid := request.Uid
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)

	orderno := Generate(time.Time{})

	orderadd := models.Ywdvipbuy{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Status:  1,
		Orderno: orderno,
		Price:   1299,
	}
	data_source.Db.Create(&orderadd)
	money2 := 1299 * 100
	if uid == 157030 || uid == 26280 {
		money2 = 1
	}

	client, err := wechat.NewClientV3(mchIdapp, mchCertificateSerialNumberapp, mchAPIv3Keyapp, mchPrivateKeyapp)
	if err != nil {
		xlog.Error(err)
		return
	}
	err = client.AutoVerifySign()
	if err != nil {
		xlog.Error(err)
		return
	}
	expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	bm.Set("appid", appidapp).
		Set("mchid", mchIdapp).
		Set("description", "测试Jsapi支付商品").
		Set("out_trade_no", orderno).
		Set("time_expire", expire).
		Set("notify_url", pturl+"/user/wechatNotifywvipapp").
		SetBodyMap("amount", func(bm gopay.BodyMap) {
			bm.Set("total", money2).
				Set("currency", "CNY")
		})

	wxRsp, err := client.V3TransactionApp(ctx, bm)
	jsapi, err := client.PaySignOfApp(appidapp, wxRsp.Response.PrepayId)
	if err != nil {
		xlog.Error(err)
		return
	}
	fmt.Print(wxRsp)
	fmt.Print(jsapi)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    jsapi,
	})
	return
}
func WechatNotifywvipapp(c *gin.Context) {

	fmt.Println(c.Request)
	notifyReq, err := wechat.V3ParseNotify(c.Request)
	fmt.Println("notifyReq", notifyReq)
	if err != nil {
		xlog.Error(err)
		return
	}
	result, err := notifyReq.DecryptCipherText(mchAPIv3Keyapp)
	fmt.Println("result.TradeState", result.TradeState)
	fmt.Println("result.TradeState", result.OutTradeNo)
	if result.TradeState == "SUCCESS" { // 验证成功
		//fmt.Println(notifyRsp["out_trade_no"].(string))
		Zhifupayvip(result.OutTradeNo)
		c.String(200, "success")
		return
	}
	c.String(200, "error")
	return
}
